﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MP3Ganizer.BusinessObject.DataToPersist;
using MP3Ganizer.BusinessObject.Services.Configuration.Builders;

namespace MP3Ganizer.BusinessObject.Services.Configuration
{
    public class ConfigurationService : MP3Ganizer.BusinessObject.Services.Configuration.IConfigurationService
    {
        private const string PATH = "Data.xml";
        private LocalConfiguration _localConfiguration;

        public ConfigurationService()
        {
            _localConfiguration = new LocalConfiguration();
        }

        public bool GetInfo(InfoType type, out object info)
        {
            info = null;
            IConfigurationBuilder builder;
            if (ConfigurationServiceFactory.Instance.TryToGetBuilderForInfoType(type, out builder))
            {
                info = builder.GetInfo(_localConfiguration);
                return info != null;
            }
            return false;
        }

        public bool GetInfos<T>(InfoType type, out IEnumerable<T> info) where T : class
        {
            info = null;
            IConfigurationBuilder builder;
            if (ConfigurationServiceFactory.Instance.TryToGetBuilderForInfoType(type, out builder))
            {
                info = builder.GetInfo(_localConfiguration) as IEnumerable<T>;
                return info != null;
            }
            return false;
        }

        public void SetInfo(InfoType type, object newInfo)
        {
            SetInfo(type, newInfo, null);
        }

        public void SetInfo(InfoType type, object newInfo, object oldInfo)
        {
            IConfigurationBuilder builder;
            if(ConfigurationServiceFactory.Instance.TryToGetBuilderForInfoType(type, out builder))
            {
                builder.SetInfo(_localConfiguration, newInfo, oldInfo);
            }
        }

        public void PersistConfig()
        {
            _localConfiguration.Save(PATH);
        }

        public void LoadConfig()
        {
            _localConfiguration.Load(PATH);
        }


        public bool DeleteInfos<T>(InfoType type, T infoToDelete) where T : class
        {
            IConfigurationBuilder builder;
            if (ConfigurationServiceFactory.Instance.TryToGetBuilderForInfoType(type, out builder))
            {
                builder.DeleteInfos(_localConfiguration, (object)infoToDelete);
                return true;
            }
            return false;
        }
    }
}
